package com.ykdl.member.kid.fragments;

import net.wxxr.dataparse.model.DataParseError;
import net.wxxr.dataparse.model.DataState;
import net.wxxr.http.interfaces.ITag;
import net.wxxr.http.request.HttpBaseRequest;
import oauth.signpost.http.HttpParameters;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ykdl.member.KidApp;
import com.ykdl.member.base.QLog;
import com.ykdl.member.constant.KidAction;
import com.ykdl.member.constant.KidConfig;
import com.ykdl.member.kid.R;
import com.ykdl.member.kid.advert.AdverltWebView;
import com.ykdl.member.kid.beans.HomeMessageCount;
import com.ykdl.member.kid.circle.TopicAndResultActivity;
import com.ykdl.member.kid.doctor.ProblemDetailsAcivity;
import com.ykdl.member.kid.gears.TopicsSheetListActivity;
import com.ykdl.member.kid.marketcard.CardScoreWapActivity;
import com.ykdl.member.kid.marketcard.CouponinfoWebView;
import com.ykdl.member.kid.marketcard.NewStoreCoupon;
import com.ykdl.member.kid.marketcard.StoreCouponActivity;
import com.ykdl.member.kid.prefs.MyPrefs;
import com.ykdl.member.kid.util.AccessTokenKeeper;
import com.ykdl.member.kid.util.RequestAsAccessTokenUtil;
import com.ykdl.member.kid.util.ResoureUtil;
import com.ykdl.net.manager.TaskManager;
import com.ykdl.net.manager.Wxxr;
public abstract class BaseFragment_home extends Fragment {
	public  View view;
	public ProgressDialog mProgressDialog;
	public Context mContext;
	public RelativeLayout set_downbut;
	public TextView mTitle,remind;
	public Button mLeft, mRight;
	private HttpBaseRequest request;
	private HomeMessageCount messageCountBean;
	public  ImageView red_point;
	@Override
	
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		red_point=(ImageView) activity.findViewById(R.id.red_point);
	};
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext = getActivity();
		
//		initMessageCount();
	}
	

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// 构建view，并且返回view
		view = initView(inflater);
//		set_downbut = (RelativeLayout) view.findViewById(R.id.set_downbut);
		/*mTitle = (TextView) view.findViewById(R.id.title);
		mLeft= (Button) view.findViewById(R.id.left);
		mRight= (Button) view.findViewById(R.id.right);
		remind = (TextView) view.findViewById(R.id.remind);*/
		return view;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		initData(savedInstanceState);
		super.onActivityCreated(savedInstanceState);
	}

	// 拿到布局填充器去填充相应的xml,生成指定的view对象
	public abstract View initView(LayoutInflater inflater);

	// view填充数据的操作
	public abstract void initData(Bundle savedInstanceState);
	
	/**
	 * 隐藏 出错的提示
	 */	
	protected void hidErrorTip( ) {
		view.findViewById(R.id.errtip_div).setVisibility(View.GONE);		
	}
	/**
	 * 设置 出错的提示
	 * @param err  err,错误提示，
	 * @param tip    tip 应该操作
	 */	
	protected void showErrorTip(String err,String tip) {
		view.findViewById(R.id.errtip_div).setVisibility(View.VISIBLE);
		((TextView)view.findViewById(R.id.tv_error_text)).setText(err);
		((TextView)view.findViewById(R.id.tv_error_text2)).setText(tip);
	}

	public final void showProgress() {
		if((this.mProgressDialog == null)
				&& (getActivity().getWindow() != null)
				&& (!getActivity().isFinishing())){
			   this.mProgressDialog = ProgressDialog
				.show(getActivity(), "", ResoureUtil.getResoure()
						.getString(R.string.progres_dialog_loading), true, false);
		}else{
			if(getActivity().getWindow() != null && (!getActivity().isFinishing())){
				this.mProgressDialog.show();
			}
		}
	}

	public final void showProgress(String paramString) {

		if (mProgressDialog == null && getActivity().getWindow() != null) {
			mProgressDialog = ProgressDialog.show(getActivity(), "", paramString, true, false);
		} else {
			if (getActivity().getWindow() != null) {
				mProgressDialog.setMessage(paramString);
				mProgressDialog.show();
			}
		}
	
	}
	public final void finishProgress() {
			
			if (mProgressDialog != null) {
				mProgressDialog.hide();
			}
//		MyProgressDialog.stop();
		}
	
	public void go(Class<?> to) {
		Intent o=	new Intent(mContext, to);	
		startActivity(o);
	}
	
	public static boolean isConnect() {
		// 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理）
		try {
			ConnectivityManager connectivity = (ConnectivityManager)KidApp.getInstance().getApplicationContext()
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			if (connectivity != null) {
				// 获取网络连接管理的对象
				NetworkInfo info = connectivity.getActiveNetworkInfo();
				if (info != null && info.isConnected()) {
					// 判断当前网络是否已经连接
					// if (info.getState() == NetworkInfo.State.CONNECTED) {
					return true;
					// }
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			QLog.debug("error", e.toString());
		}
		return false;
	}
	/**
	 * 根据action 跳转到到不同的页面，主要是展位在使用
	 * @param paction
	 * @param pbean
	 */
	public void goAction(String paction) {
		if(paction==null){
			return;
		}


		//进圈子
		//lmyr://subject/10/786326
	    //"http://tool.test.com/group/1",
		 //进帖子
	    //"http://tool.test.com/subject/1/2",
		//问医生
	    //"http://docask/1",
		 //医生专题
	    //"http://tool.test.com/docspec/1/asfafa%32%32%32%32adsfas",
		//普通专题
	    //"http://tool.test.com/hotspec/1/asfadsfasdfasf",
		
		if(TextUtils.isEmpty(paction))return;
		if (paction.startsWith("http:")) {
			Intent intent = new Intent(mContext,AdverltWebView.class);
			intent.putExtra(KidAction.INTENT_URL, paction+"");
			startActivity(intent);
		}else {
			String[] end = paction.split("\\//")[1].split("\\/");
			Intent intent = null;
			 if (paction.contains("lottery_game")) {//游戏
				 intent = new Intent(mContext, CouponinfoWebView.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					intent.putExtra(KidAction.LOTTERY_ID, end[1]);
					if (end[2].equals("1")) {
						intent.putExtra(KidAction.URL_TYPE, 5);
					}else{
						intent.putExtra(KidAction.URL_TYPE, 6);
					}
			} else if (paction.contains("exchange_charitable")){//积分慈善
				intent = new Intent(mContext, CardScoreWapActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				intent.putExtra(KidAction.URL_TYPE, 3);
				intent.putExtra(KidAction.POINT_TYPE_ID, end[1]);
			} else if (paction.contains("exchange_lottery")){//积分抽奖
				intent = new Intent(mContext, CardScoreWapActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				intent.putExtra(KidAction.URL_TYPE, 2);
				intent.putExtra(KidAction.POINT_TYPE_ID, end[1]);
				
			}  else if (paction.contains("exchange")){//积分换礼
				intent = new Intent(mContext, CardScoreWapActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				intent.putExtra(KidAction.URL_TYPE, 0);
				intent.putExtra(KidAction.POINT_TYPE_ID, end[1]);
			} else if (paction.contains("product_list")){//商品列表
				intent = new Intent(mContext, NewStoreCoupon.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				intent.putExtra(KidAction.STORE_ID, end[1]);
				intent.putExtra(KidAction.IS_STORE, true);
			} else if(paction.contains("coupon_list")){//优惠卷列表
				intent = new Intent(mContext, NewStoreCoupon.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				intent.putExtra(KidAction.STORE_ID, end[1]);
				intent.putExtra(KidAction.IS_STORE, false);
			}else if (paction.contains("subject")) {// 进帖子详情
				intent = new Intent(mContext, TopicAndResultActivity.class);
				intent.putExtra(TopicAndResultActivity.STR_TOPIC_ID, end[2]);
				intent.putExtra(TopicAndResultActivity.STR_GROUP_ID, end[1]);
			}
			 if(intent ==null)return;
			 startActivity(intent);
			}
		}
	private void initMessageCount() {
		AccessTokenKeeper keeper = new AccessTokenKeeper(mContext);
		if(keeper.getmisAnonymous()) return;
		if(!isConnect())return;
		String url = KidConfig.UNREAD_NEWS_COUNT ;
		HttpParameters bodyParams = new HttpParameters();
		request = Wxxr.getInstance().postBaseRequest(url, bodyParams,null
				);
		TaskManager.startHttpRequest(request, new getMessageCountTag(),
				HomeMessageCount.class);
		
	}
	
	class getMessageCountTag implements ITag{
		@Override
		public void refreshUI(Object t, DataState ds) {
			if(null != t && t instanceof HomeMessageCount){
				messageCountBean = (HomeMessageCount)t;
				if(messageCountBean.isExpired()){
					RequestAsAccessTokenUtil.getInstance(mContext).refreshTokenRequest(request, this, HomeMessageCount.class);
				}else{
					settingMessageCount();
				}
			}
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			return true;
		}

		@Override
		public void refreshCancel() {
		}
	}
	
	/**
	 * 设置信息数量汇总
	 */
	public void settingMessageCount() {
		if (messageCountBean.getUnread_count() > 0) {
			red_point.setVisibility(view.VISIBLE);
			MyPrefs.setMessageCount(mContext, "1");
		}else {
			red_point.setVisibility(view.GONE);
			MyPrefs.setMessageCount(mContext, null);
		}
	}

}
